package com.ygqh.baby.controller.mobile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.model.MediaItem;
import com.foxinmy.weixin4j.model.WeixinAccount;
import com.foxinmy.weixin4j.mp.model.Following;
import com.foxinmy.weixin4j.mp.model.Menu;
import com.foxinmy.weixin4j.mp.model.User;
import com.foxinmy.weixin4j.tuple.MassTuple;
import com.foxinmy.weixin4j.tuple.Text;
import com.foxinmy.weixin4j.type.MediaType;
import com.foxinmy.weixin4j.util.NameValue;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.ao.PromotionType;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.ao.WxMessageType;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.model.wdt.WdtResult;
import com.ygqh.baby.model.wdt.qyb.WdtGoosSpecPushReq;
import com.ygqh.baby.model.wdt.qyb.WdtQybResult;
import com.ygqh.baby.model.wdt.qyb.WdtSyncLogisticsResult;
import com.ygqh.baby.model.wx.WxButton;
import com.ygqh.baby.po.AdminPurchase;
import com.ygqh.baby.po.YgCommission;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgPlatform;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgReturnOrder;
import com.ygqh.baby.po.YgSku;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.AdminPurchaseService;
import com.ygqh.baby.service.KsdOrderService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.WxMpMessageService;
import com.ygqh.baby.service.WxSmallMessageService;
import com.ygqh.baby.service.YgCommissionDetailService;
import com.ygqh.baby.service.YgCommissionService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.YgPlatformService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.YgReturnOrderService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.service.linkstars.YgLinkStarsService;
import com.ygqh.baby.service.linkstars.model.LSResult;
import com.ygqh.baby.service.task.WdtService;
import com.ygqh.baby.service.task.YgAsynClient;
import com.ygqh.baby.service.wdtqyb.api.WdtQybApi;
import com.ygqh.baby.service.wdtqyb.exception.WdtException;
import com.ygqh.baby.service.wechat.WxConfig;
import com.ygqh.baby.service.weixin.WxTemplateMessageService;
import com.ygqh.baby.service.weixin.model.WxTemplateMessage;
import com.ygqh.baby.service.weixin.token.WxTokenManager;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.VerifyCodeUtils;
import com.ygqh.baby.utils.WebUtils;

import redis.clients.jedis.Transaction;

/**
 * 微信相关接口
 * 
 * @author guohao
 *
 */
@Controller
@RequestMapping("/mobile/weixin")
public class YgWeChatController extends BaseController {

	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private WxMpMessageService wxMpMessageService;
	@Autowired
	private DocumentConstant documentConstant;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private WdtService wdtService;
	@Autowired
	private AdminPurchaseService adminPurchaseService;
	@Autowired
	private YgReturnOrderService ygReturnOrderService;
	@Autowired
	private YgCommissionService ygCommissionService;
	@Autowired
	private YgCommissionDetailService ygCommissionDetailService;
	@Autowired
	private YgLinkStarsService ygLinkStarsService;
	@Autowired
	private WdtQybApi wdtQybApi;
	@Autowired
	private YgProductService ygProductService;
	@Autowired
	private YgAsynClient ygAsynClient;
	@Autowired
	private KsdOrderService ksdOrderService;
	@Autowired
	private WxSmallMessageService wxSmallMessageService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgPlatformService ygPlatformService;
	@Autowired
	private WxTemplateMessageService wxTemplateMessageService;
	@Autowired
	private WxTokenManager wxTokenManager;

	@RequestMapping(value = "sendMsgNew", method = RequestMethod.GET)
	@ResponseBody
	public Message sendMsgNew(String platformNo, HttpServletRequest request, HttpServletResponse response) throws WdtException {
		// String accessToken =
		// wxTokenManager.getAccessToken("wxf2551b8e06b39c2d",
		// "d4624c36b6795d1d99dcf0547af5443d");

		WeixinAccount weixinAccount = WxConfig.getWxaccount();
		String url = "http://m.yiigoo.com";
		Map<String, NameValue> contentMap = new HashMap<>();
		contentMap.put("keyword1", new NameValue("#323232", "申通快递"));
		contentMap.put("keyword2", new NameValue("#323232", "2123123"));
		contentMap.put("keyword3", new NameValue("#323232", "2123123"));
		contentMap.put("remark", new NameValue("#323232", "订单编号：123456 \n商品名称：wahaha"));

		WxTemplateMessage wxTemplateMessage = wxTemplateMessageService.assemblyTemplateMessage(WxMessageType.AuditResultMsg, weixinAccount,
				"obgV1vwlKt_NpMk5lo0ZqrxFu9sI", url, contentMap);
		Message message = wxTemplateMessageService.sendTemplateMessage(wxTemplateMessage);
		return message;
	}

	@RequestMapping(value = "getPlatform", method = RequestMethod.GET)
	@ResponseBody
	public YgPlatform getPlatform(String platformNo, HttpServletRequest request, HttpServletResponse response) throws WdtException {
		YgPlatform findByPlatformNo = ygPlatformService.findByPlatformNo("001");
		return findByPlatformNo;
	}

	@RequestMapping(value = "updatePlatform", method = RequestMethod.GET)
	@ResponseBody
	public YgPlatform updatePlatform(String platformNo, HttpServletRequest request, HttpServletResponse response) throws WdtException {
		YgPlatform findByPlatformNo = ygPlatformService.findByPlatformNo("001");
		findByPlatformNo.setRemark("wahahahahaah");
		int saveOrUpdate = ygPlatformService.update(findByPlatformNo);
		return findByPlatformNo;
	}

	@RequestMapping(value = "queryShop", method = RequestMethod.GET)
	@ResponseBody
	public String queryShop(HttpServletRequest request, HttpServletResponse response) throws WdtException {
		wdtQybApi.queryShop("002", null, 0, 100);
		return "";
	}

	@RequestMapping(value = "sendGroupOrderRemindMsg", method = RequestMethod.GET)
	@ResponseBody
	public String sendGroupOrderRemindMsg(HttpServletRequest request, HttpServletResponse response) throws WdtException {
		String title = "亲，您的拼团商品  wahaha  件数还不够哦。";
		Long orderId = 180507978909L;
		String formId = "95b5055835794735ad5aace71d916704";
		String page = "pages/user/orderdetail/orderdetail?orderId=" + orderId;
		wxSmallMessageService.sendGroupOrderRemindMsg(title, "wahaha", 1L, DateConvertUtils.addMinute(new Date(), 20), "快去分享给您的好友一起拼团吧.", orderId, formId, page,
				"ofsAn444OFt1_Vusy7TzC85A9o6w");
		return "";
	}

	@RequestMapping(value = "setid", method = RequestMethod.GET)
	@ResponseBody
	public String setid() throws WdtException {
		String set = redisDao.set("user_action_set_id_WEB", "1106758649", 0);
		return set;
	}

	@RequestMapping(value = "reidsMultiTest", method = RequestMethod.GET)
	@ResponseBody
	public String reidsMultiTest(HttpServletRequest request, HttpServletResponse response) throws YgException, IOException, WeixinException {
		ExecutorService pool = Executors.newFixedThreadPool(5);
		final String key = "TEST--";
		for (int i = 0; i < 400; i++) {
			final int index = i;
			pool.execute(new Runnable() {

				@Override
				public void run() {

					redisDao.watch(key);
					String str = redisDao.get(key);
					Transaction tx = redisDao.multi();
					tx.set(key, index + "");
					List<Object> exec = tx.exec();
					System.out.println("index = " + index + " ===" + exec.toString());
				}
			});
		}
		return "";

	}

	@RequestMapping(value = "refundQueryWdt", method = RequestMethod.GET)
	@ResponseBody
	public String refundQueryWdt(HttpServletRequest request, HttpServletResponse response) throws WdtException {
		// String openId = "oFtUR024P7jaNUGqn644suUaponY";
		Date startTime = DateConvertUtils.parse("2017-09-01 00:00:00", DateConvertUtils.DATE_TIME_FORMAT);
		WdtQybResult refundQuery = null;
		for (;;) {
			Date endTime = DateConvertUtils.addMinute(startTime, 60);

			refundQuery = wdtQybApi.refundQuery(90, startTime, endTime, 0, 40, null, null);
			System.out.println(JSON.toJSONString(refundQuery));
			startTime = endTime;
		}
	}

	@RequestMapping(value = "getMassNewStatus", method = RequestMethod.GET)
	@ResponseBody
	public String getMassNewStatus(HttpServletRequest request, HttpServletResponse response) throws YgException, IOException, WeixinException {
		// String openId = "oFtUR024P7jaNUGqn644suUaponY";
		String openId = "oFtUR024P7jaNUGqn644suUaponY";
		Message message = wxMpMessageService.sendSubscribeMsg(openId, "一次性订阅消息测试", "CEbGeG9rrMSbJpkSNl6qfTZUlOv4Sn2mntN9DIZeVK0", "http://m.yiigoo.com", "1000",
				"hahahaha");
		return message.toString();
	}

	@RequestMapping(value = "getGroupId", method = RequestMethod.GET)
	@ResponseBody
	public Integer getGroupId(HttpServletRequest request, HttpServletResponse response) throws YgException, IOException, WeixinException {
		// Following userList = wxMpAuthorityService.findUserList(null);
		/*
		 * MassApi api = new MassApi(wxMpAuthorityService.findTokenHolder());
		 * MassTuple tuple = new Text("openid:"+"oFtUR024P7jaNUGqn644suUaponY"+
		 * "oFtUR0_AmXuEaQKdfO9aG2KFL86c"); String[] massByOpenIds =
		 * api.massByOpenIds(tuple, new String[]{"oFtUR024P7jaNUGqn644suUaponY",
		 * "oFtUR0_AmXuEaQKdfO9aG2KFL86c" });
		 * System.out.println(massByOpenIds[0]+";"+massByOpenIds[1]);
		 */
		int groupId = wxMpAuthorityService.getGroupId("技术");

		return 1;
	}

	@RequestMapping(value = "sendAllMsg", method = RequestMethod.GET)
	public void sendAllMsg(HttpServletRequest request, HttpServletResponse response) throws YgException, IOException, WeixinException {
		int groupId = 102;
		boolean isToAll = false;
		MassTuple tuple = new Text("2-isToAll：" + isToAll + ";groupId:" + 102);
		wxMpAuthorityService.sendAllMsg(tuple, isToAll, groupId);
	}

	@RequestMapping(value = "imgCode", method = RequestMethod.GET)
	public void imgCode(HttpServletRequest request, HttpServletResponse response) throws YgException, IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		// 生成图片
		int w = 100, h = 50;
		VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
	}

	@RequestMapping(value = "threadPool", method = RequestMethod.GET)
	@ResponseBody
	public String threadPool(HttpServletRequest request) throws YgException, WeixinException {
		ksdOrderService.paySuccess("161213609110", "1212", "obgV1vwlKt_NpMk5lo0ZqrxFu9sI", new BigDecimal(39));
		return "";

	}

	@RequestMapping(value = "orderPush", method = RequestMethod.GET)
	@ResponseBody
	public LSResult orderPush(HttpServletRequest request) throws YgException {

		YgOrder order = ygOrderService.findOrderDetailByOrderId(170510452909L);
		LSResult result = ygLinkStarsService.orderPush(order);
		return result;
	}

	@RequestMapping(value = "effectPush", method = RequestMethod.GET)
	@ResponseBody
	public LSResult effectPush(HttpServletRequest request) {
		// 170424539417L
		YgOrder order = ygOrderService.findOrderDetailByOrderId(170425895640L);
		List<YgOrder> oList = new ArrayList<YgOrder>();
		oList.add(order);
		LSResult result = ygLinkStarsService.effectPush(oList);
		return result;
	}

	@RequestMapping(value = "addKFAccount", method = RequestMethod.GET)
	@ResponseBody
	public String addKFAccount(HttpServletRequest request) {
		wxMpAuthorityService.addKFAccount();
		return "";
	}

	@RequestMapping(value = "getWeChatMessage", method = RequestMethod.GET)
	@ResponseBody
	public String getWeChatMessage(HttpServletRequest request) {
		String authorizeURL = "";
		try {
			authorizeURL = wxMpAuthorityService.getAuthorizeURL("state", "snsapi_base", "http://m.yiigoo.com/order/submitSuccess.html");
		} catch (WeixinException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		return authorizeURL;
	}

	@RequestMapping("getAccessToken")
	public String getAccessToken(String cmd, HttpServletRequest request, Model model, HttpServletResponse response) throws Exception {
		return "test";
	}

	@RequestMapping("publishMenu")
	@ResponseBody
	public void publishMenu(@RequestParam(required = true) String url, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TokenHolder tokenHolder = wxMpAuthorityService.findTokenHolder();
		// HelperApi HelperApi = new HelperApi(tokenHolder);
		// String shorturl = HelperApi.getShorturl("pages/index");
		List<WxButton> list = new ArrayList<WxButton>();
		wxMpAuthorityService.publishCustomMenu(list);
	}

	@RequestMapping("getAllMenu")
	@ResponseBody
	public JSONPObject getAllMenu(String callback) throws Exception {

		List<Menu> allMenu = wxMpAuthorityService.getAllMenu();
		return new JSONPObject(callback, Message.success(allMenu));
	}

	@RequestMapping("test")
	@ResponseBody
	public JSONPObject publishMenus(String callback, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String samllQrcode = wxMpAuthorityService.getShortUrl(" http://m.yiigoo.com");
		return new JSONPObject(callback, Message.success(samllQrcode));
	}

	@RequestMapping("sendMsg")
	@ResponseBody
	public JSONPObject sendMsg(String callback, HttpServletRequest request, HttpServletResponse response) throws Exception {
		YgUser user = ygUserService.findById(55l);
		Message sendBindMsg = wxMpMessageService.sendGoods4Change("申通", "123456", "哇哈哈", 123456l, 55l);

		System.out.println(00);
		return new JSONPObject(callback, Message.success(sendBindMsg));
	}

	@RequestMapping("getQrcodeUrl")
	@ResponseBody
	public JSONPObject getQrcodeUrl(String callback) throws WeixinException {
		JSONPObject json = null;
		String codeUrl = wxMpAuthorityService.findQrCodeUrl("wei");
		Map<String, String> map = new HashMap<String, String>();
		map.put("codeUrl", codeUrl);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	@RequestMapping("getWdtOrder")
	@ResponseBody
	public JSONPObject getWdtOrder(String tradeNo, String callback) throws WeixinException {
		JSONPObject json = null;
		// YgOrder ygOrder =
		// ygOrderService.findOrderDetailByOrderId(161024879772l);
		// WdtResult result = wdtService.createOrder(ygOrder);
		WdtResult result = wdtService.QueryTradeByNO(tradeNo);
		// WdtResult result = wdtService.QueryStockinOrder(null, 40, 0,
		// DateConvertUtils.addMinute(new Date(), -40),
		// DateConvertUtils.addMinute(new Date(), -1));
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, result));
		return json;
	}

	@RequestMapping("cancelOrder")
	@ResponseBody
	public JSONPObject CancelOrder(String tradeNo, String callback) throws WeixinException {
		JSONPObject json = null;
		WdtResult result = wdtService.CancelOrder("CG20161109002", 2, "000", 1);
		// WdtResult result = wdtService.QueryStockinOrder(null, 40, 0,
		// DateConvertUtils.addMinute(new Date(), -40),
		// DateConvertUtils.addMinute(new Date(), -1));
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, result));
		return json;
	}

	@RequestMapping("createStockInOrder")
	@ResponseBody
	public JSONPObject createStockInOrder(String tradeNo, String callback) throws WeixinException {
		JSONPObject json = null;
		// AdminPurchase purchase = adminPurchaseService.findPurchaseByCode("");
		// YgOrder ygOrder =
		// ygOrderService.findOrderDetailByOrderId(161019556524l);
		YgReturnOrder returnCode = ygReturnOrderService.findDetailByReCode("H161205834352");
		WdtResult result = wdtService.createChangeOrder(returnCode);
		// WdtResult result = wdtService.createStockInOrder(purchase);
		// WdtResult result = wdtService.QueryStockinOrder(null, 40, 0,
		// DateConvertUtils.addMinute(new Date(), -40),
		// DateConvertUtils.addMinute(new Date(), -1));
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, result));
		return json;
	}

	@RequestMapping("getStockOrderList")
	@ResponseBody
	public JSONPObject getStockOrderList(String tradeNo, String callback) throws WeixinException {
		JSONPObject json = null;
		/*
		 * WdtQueryStockinOrder result = (WdtQueryStockinOrder)
		 * wdtService.QueryStockinOrder(null, 1, 30,
		 * DateConvertUtils.addMinute(new Date(), -55),
		 * DateConvertUtils.addMinute(new Date(), -1));
		 */
		// ygTaskService.syncStockOrderTask(60);
		WdtResult queryPurchaseOrder = wdtService.queryPurchaseOrder("CG20161109010", DateConvertUtils.addMinute(new Date(), -60),
				DateConvertUtils.addMinute(new Date(), -1), 0, 1, 50);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, queryPurchaseOrder));
		return json;
	}

	@RequestMapping("getAllMaterialMedia")
	@ResponseBody
	public JSONPObject getAllMaterialMedia(String tradeNo, String callback) throws WeixinException {
		JSONPObject json = null;
		List<MediaItem> list = wxMpAuthorityService.getAllMaterialMedia(MediaType.image);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, list));
		return json;
	}

	@RequestMapping("getShortUrl")
	@ResponseBody
	public JSONPObject getShortUrl(String url, String callback) throws WeixinException {
		JSONPObject json = null;
		String shortUrl = WebUtils.generateShortUrl(url);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, shortUrl));
		return json;
	}

	@RequestMapping("getLogisticsInfo")
	@ResponseBody
	public JSONPObject getLogisticsInfo(String url, String callback) throws WeixinException {
		JSONPObject json = null;
		String shortUrl = WebUtils.generateShortUrl(url);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, shortUrl));
		return json;
	}

	@RequestMapping("repairData")
	@ResponseBody
	public JSONPObject repairData(String url, String callback) throws WeixinException {

		ResultSet<YgCommission> search = ygCommissionService.search(null, null, null, null);
		List<YgCommission> result = search.getResult();
		result.stream().sorted(new Comparator<YgCommission>() {

			@Override
			public int compare(YgCommission o1, YgCommission o2) {
				if (o1.getId().intValue() < o2.getId().intValue()) {
					return 1;
				} else if (o1.getId().intValue() > o2.getId().intValue()) {

					return -1;
				} else {

					return 0;
				}
			}
		}).map(commission -> {

			System.out.println("map====" + commission.getId());
			return commission;
		}).forEach(commission -> {
			ygCommissionDetailService.addCommisssionDetail(commission.getId(), commission.getCommissionPrice(), commission.getUserId());
			System.out.println("forEach====" + commission.getId());
		});

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, result));
	}

	@RequestMapping("syncOrders")
	@ResponseBody
	public JSONPObject syncOrders(Long orderId, String callback) throws Exception {

		List<Long> orderIds = new ArrayList<Long>();
		orderIds.add(170629462597l);
		orderIds.add(170629462596l);
		ygAsynClient.syncQybOrder(orderIds);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, ""));

	}


	@RequestMapping("applyRefund")
	@ResponseBody
	public JSONPObject applyRefund(String returnCode, String callback) throws Exception {
		YgReturnOrder returnOrder = ygReturnOrderService.findDetailByReCode(returnCode);
		WdtQybResult tradePush = wdtQybApi.applyRefund(returnOrder, null);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("pushChangeOrderBefore")
	@ResponseBody
	public JSONPObject pushChangeOrderBefore(String returnCode, String callback) throws Exception {
		YgReturnOrder returnOrder = ygReturnOrderService.findDetailByReCode(returnCode);
		WdtQybResult tradePush = wdtQybApi.pushChangeOrderBefore(returnOrder, null);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("pushChangeOrderAfter")
	@ResponseBody
	public JSONPObject pushChangeOrderAfter(String returnCode, String callback) throws Exception {
		YgReturnOrder returnOrder = ygReturnOrderService.findDetailByReCode(returnCode);
		WdtQybResult tradePush = wdtQybApi.pushChangeOrderAfter(returnOrder);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("tradeQuery")
	@ResponseBody
	public JSONPObject tradeQuery(Long orderId, String callback) throws Exception {

		WdtQybResult tradePush = wdtQybApi.tradeQuery(0, DateConvertUtils.addMinute(new Date(), -10), DateConvertUtils.addMinute(new Date(), -1), 0);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("changeOrderpush")
	@ResponseBody
	public JSONPObject changeOrderpush(String changeCode, String callback) throws Exception {
		YgReturnOrder returnOrder = ygReturnOrderService.findDetailByReCode(changeCode);
		WdtQybResult tradePush = wdtQybApi.pushChangeOrderBefore(returnOrder, null);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("syncSkuStock")
	@ResponseBody
	public JSONPObject syncSkuStock(Long orderId, String callback) throws Exception {

		WdtQybResult tradePush = wdtQybApi.syncSkuStock(2000);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("queryStockIn")
	@ResponseBody
	public JSONPObject queryStockIn(Long orderId, String callback) throws Exception {

		WdtQybResult tradePush = wdtQybApi.queryStockIn(DateConvertUtils.addMinute(new Date(), -180), DateConvertUtils.addMinute(new Date(), -130), 1, 0, 30);

		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("queryStockOut")
	@ResponseBody
	public JSONPObject queryStockOut(Long orderId, String callback) throws Exception {

		WdtQybResult tradePush = wdtQybApi.queryStockOut(DateConvertUtils.addMinute(new Date(), -50), DateConvertUtils.addMinute(new Date(), -1), 1, "", "",
				30);
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("syncLogistics")
	@ResponseBody
	public JSONPObject syncLogistics(Long orderId, String callback) throws Exception {

		WdtSyncLogisticsResult tradePush = wdtQybApi.syncLogistics(100, 1);
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("purchasePush")
	@ResponseBody
	public JSONPObject purchasePush(Long orderId, String callback) throws Exception {
		AdminPurchase purchase = adminPurchaseService.findPurchaseByCode("J17061301");
		WdtQybResult tradePush = wdtQybApi.purchasePush(purchase);
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, tradePush));

	}

	@RequestMapping("goodsSpecPush")
	@ResponseBody
	public JSONPObject goodsSpecPush(Long orderId, String callback) throws Exception {
		// 50006004
		List<YgProduct> products = ygProductService.findByProductCodes(new String[] { "50001803" }, PromotionType.Ordinary);
		List<WdtGoosSpecPushReq> list = new ArrayList<WdtGoosSpecPushReq>();
		for (YgProduct ygProduct : products) {
			for (YgSku sku : ygProduct.getYgSkus()) {
				WdtGoosSpecPushReq goods = new WdtGoosSpecPushReq(1, ygProduct.getProductCode(), ygProduct.getProductName(), sku.getSkuCode(),
						ygProduct.getShortName() + " " + sku.getSizeName());
				list.add(goods);
			}
		}
		WdtQybResult result = wdtQybApi.goodsSpecPush(list);
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, result));

	}

	@RequestMapping("queryTradeByNO")
	@ResponseBody
	public JSONPObject queryTradeByNO(String orderId, String callback) throws Exception {
		WdtQybResult result = wdtQybApi.tradeQuery(0, DateConvertUtils.addMinute(new Date(), -100), DateConvertUtils.addMinute(new Date(), -1), 0, orderId);
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, result));

	}

	@RequestMapping("repairData1")
	@ResponseBody
	public JSONPObject repairData(Date startDate, HttpServletRequest request, String callback) throws WeixinException {
		String nextOpenId = null;
		Boolean falg = true;
		List<String> openIds = new ArrayList<String>();
		Following following = null;
		while (falg) {
			following = wxMpAuthorityService.findUserList(nextOpenId);
			List<User> userList = following.getUserList();
			for (int i = 0; i < userList.size(); i++) {
				openIds.add(userList.get(i).getOpenId());
				if (openIds.size() == 500 || i == userList.size() - 1) {
					ygUserService.updateSubscribeStatusBatch(openIds, true);
					openIds.clear();
				}
			}

			if (following.getCount() >= 10000) {
				nextOpenId = following.getNextOpenId();
			} else {
				falg = false;
			}
		}
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, following));
	}

}
